package cn.dida.controller;

import cn.dida.model.HttpResponseBodyWrapper;
import cn.dida.model.Pageable;
import cn.dida.model.SalesmanPayrule;
import cn.dida.model.UserSession;
import cn.dida.service.SalesmanCashService;
import cn.dida.util.DateUtils;
import cn.dida.util.ExcelUtil;
import com.alibaba.fastjson.JSONArray;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.*;

/**
 * Created by zhangzhiling on 2017/9/1.
 */
@Controller
@RequestMapping("/salesmanCash")
public class SalesmanCashController extends BaseController {

    @Autowired
    private SalesmanCashService cashService;

    /**
     * 提现申请列表
     * @param request
     * @param proName
     * @param saleman
     * @param timeLimitStart
     * @param timeLimitEnd
     * @param page
     * @return
     * @throws Exception
     */
    @GetMapping("/list")
    public ModelAndView queryList(HttpServletRequest request, String proName, String saleman, String timeLimitStart, String timeLimitEnd , Integer page) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);
        page = (page == null || page < 1) ? 1 : page;
        proName = StringUtils.trimToNull(proName);
        saleman = StringUtils.trimToNull(saleman);
        Pageable<Map<String,Object>> result = cashService.queryList(userSession.getCompanyId(),proName,saleman,timeLimitStart,timeLimitEnd,page);
        model.put("pagelist", result);
        model.put("proName", proName);
        model.put("saleman", saleman);
        model.put("timeLimitStart", timeLimitStart);
        model.put("timeLimitEnd", timeLimitEnd);
        return new ModelAndView("salesman_cash_list").addAllObjects(model);
    }

    /**
     *  提现申请 导出
     * @param request
     * @param response
     * @param proName
     * @param saleman
     * @param timeLimitStart
     * @param timeLimitEnd
     * @return
     * @throws Exception
     */
    @GetMapping("/export")
    public ModelAndView export(HttpServletRequest request, HttpServletResponse response,String proName, String saleman, String timeLimitStart, String timeLimitEnd) throws Exception {
        UserSession userSession = getUserSession(request);

        List<Map<String,Object>> exportList = cashService.exportList(userSession.getCompanyId(), proName, saleman,timeLimitStart,timeLimitEnd);

        String fileName = "提现申请数据导出" + DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(exportList.size());

        Map<String, Object> fmap = null;
        for (Map<String,Object> obj : exportList) {
            fmap = new HashMap<String, Object>();
            fmap.put("code", obj.get("code"));
            fmap.put("proName", obj.get("proName"));
            fmap.put("num", obj.get("num"));
            fmap.put("salesmanCode", obj.get("salesmanCode"));
            fmap.put("salesmanName", obj.get("salesmanName"));
            fmap.put("c_time",DateUtils.transferLongToDate("yyyy-MM-dd HH:mm:ss", (Long)obj.get("c_time")));
            Integer state = (Integer) obj.get("pay_state");
            if(state == 0){
                fmap.put("state", "未支付");
            }else if(state == 2){
                fmap.put("state", "支付中");
            }else{
                fmap.put("state", "支付失败");
            }
            list.add(fmap);
        }

        String columnNames[] = {"申请编码", "提现产品", "瓶数", "促销员编号",  "促销员姓名",  "申请时间","状态"};//列名
        String keys[] = {"code", "proName", "num", "salesmanCode", "salesmanName", "c_time","state"};//map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
                bos.flush();
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }

        return null;
    }

    /**
     * 单条记录支付
     * @param request
     * @param payment
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PutMapping("/pay")
    public HttpResponseBodyWrapper PaymentlistSave(HttpServletRequest request, @RequestBody Map<String, Object> payment) throws Exception {

        UserSession userSession = getUserSession(request);
        Boolean result = true;
        System.out.println(payment.toString());
        if(payment.containsKey("cashId") && payment.containsKey("openid")
                && payment.containsKey("totalprize") && payment.containsKey("salesman_id")){
            cashService.paymentSave(userSession.getCompanyId(),(Integer) payment.get("cashId"),
                    Float.parseFloat((String)payment.get("totalprize")),Integer.parseInt((String)payment.get("salesman_id")),(String) payment.get("openid"));
        }

        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 批量支付
     * @param request
     * @param payment
     * @return
     * @throws Exception
     */
    @ResponseBody
    @PutMapping("/batch_pay")
    public HttpResponseBodyWrapper batch_pay(HttpServletRequest request, @RequestBody Map<String, Object> payment) throws Exception {

        UserSession userSession = getUserSession(request);
        Boolean result = true;
        System.out.println(payment.toString());
        if(payment.containsKey("List") ){
            JSONArray js = JSONArray.parseArray(payment.get("List").toString());
            cashService.paymentSave_batch_pay(js,userSession.getCompanyId());
        }
//        if(payment.containsKey("cashId") && payment.containsKey("openid")
//                && payment.containsKey("totalprize") && payment.containsKey("salesman_id")){
//            cashService.paymentSave(userSession.getCompanyId(),(Integer) payment.get("cashId"),
//                    Float.parseFloat((String)payment.get("totalprize")),Integer.parseInt((String)payment.get("salesman_id")),(String) payment.get("openid"));
//        }

        return new HttpResponseBodyWrapper(result);
    }

    /**
     * 已支付列表
     * @param request
     * @param proName
     * @param saleman
     * @param timeLimitStart
     * @param timeLimitEnd
     * @param page
     * @return
     * @throws Exception
     */
    @GetMapping("/paidList")
    public ModelAndView paidList(HttpServletRequest request, String proName, String saleman, String timeLimitStart, String timeLimitEnd , Integer page) throws Exception {
        Map<String, Object> model = new HashMap();
        UserSession userSession = getUserSession(request);
        page = (page == null || page < 1) ? 1 : page;
        proName = StringUtils.trimToNull(proName);
        saleman = StringUtils.trimToNull(saleman);
        Pageable<Map<String,Object>> result = cashService.queryPaidList(userSession.getCompanyId(),proName,saleman,timeLimitStart,timeLimitEnd,page);
        model.put("pagelist", result);
        model.put("proName", proName);
        model.put("saleman", saleman);
        model.put("timeLimitStart", timeLimitStart);
        model.put("timeLimitEnd", timeLimitEnd);
        return new ModelAndView("salesman_paid_list").addAllObjects(model);
    }

    /**
     * 已支付导出
     * @param request
     * @param response
     * @param proName
     * @param saleman
     * @param timeLimitStart
     * @param timeLimitEnd
     * @return
     * @throws Exception
     */
    @GetMapping("/exportPaid")
    public ModelAndView paid_export(HttpServletRequest request, HttpServletResponse response,String proName, String saleman, String timeLimitStart, String timeLimitEnd) throws Exception {
        UserSession userSession = getUserSession(request);

        List<Map<String,Object>> exportList = cashService.exportPaidList(userSession.getCompanyId(), proName, saleman,timeLimitStart,timeLimitEnd);

        String fileName = "已支付数据导出" + DateUtils.dateToString(Calendar.getInstance().getTime(), "yyyy-MM-dd");

        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>(exportList.size());

        Map<String, Object> fmap = null;
        for (Map<String,Object> obj : exportList) {
            fmap = new HashMap<String, Object>();
            fmap.put("code", obj.get("code"));
            fmap.put("proName", obj.get("proName"));
            fmap.put("num", obj.get("num"));
            fmap.put("salesmanName", obj.get("salesmanName"));
            fmap.put("phone", obj.get("phone"));
            fmap.put("pay_price", obj.get("pay_price"));
            fmap.put("c_time",DateUtils.transferLongToDate("yyyy-MM-dd HH:mm:ss", (Long)obj.get("c_time")));
            fmap.put("pay_time",DateUtils.transferLongToDate("yyyy-MM-dd HH:mm:ss", (Long)obj.get("pay_time")));
            fmap.put("state", "成功");
            list.add(fmap);
        }

        String columnNames[] = {"申请编码", "提现产品", "瓶数", "促销员姓名",  "手机号码", "金额", "申请时间","支付时间","状态"};//列名
        String keys[] = {"code", "proName", "num", "salesmanName", "phone", "pay_price","c_time","pay_time","state"};//map中的key
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        try {
            ExcelUtil.createWorkBook(list, keys, columnNames).write(os);
        } catch (IOException e) {
            e.printStackTrace();
        }
        byte[] content = os.toByteArray();
        InputStream is = new ByteArrayInputStream(content);
        // 设置response参数，可以打开下载页面
        response.reset();
        response.setContentType("application/vnd.ms-excel;charset=utf-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xls").getBytes(), "iso-8859-1"));
        ServletOutputStream out = response.getOutputStream();
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;
        try {
            bis = new BufferedInputStream(is);
            bos = new BufferedOutputStream(out);
            byte[] buff = new byte[2048];
            int bytesRead;
            // Simple read/write loop.
            while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                bos.write(buff, 0, bytesRead);
                bos.flush();
            }
        } catch (final IOException e) {
            throw e;
        } finally {
            if (bis != null)
                bis.close();
            if (bos != null)
                bos.close();
        }

        return null;
    }
}
